package com.tensquare.util;

import com.tensquare.constants.TokenConstants;
import com.tensquare.entity.JWTInfo;
import com.tensquare.exception.UserTokenException;
import io.jsonwebtoken.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.concurrent.TimeUnit;

public class JwtTokenUtil {

    public static String generateToken(JWTInfo jwtInfo, String secretKey) {
        long l = System.currentTimeMillis() + 1000 * 60 * 60 * 4;
        return Jwts.builder()
                .setSubject(jwtInfo.getAccount())
                .claim(TokenConstants.JWT_KEY_id,jwtInfo.getId())
                .claim(TokenConstants.JWT_KEY_NICKNAME,jwtInfo.getNickname())
                .claim(TokenConstants.JWT_KEY_USER_ACCOUNT,jwtInfo.getAccount())
                .setIssuedAt(new Date())//签发时间
                .setExpiration(new Date(l))//过期时间
                .signWith(SignatureAlgorithm.HS256, secretKey)
                .compact();
    }

    public static Claims getInfoFromToken(String authToken,String secretKey) throws Exception {
        try {
            return Jwts.parser().setSigningKey(secretKey).parseClaimsJws(authToken).getBody();
        } catch (ExpiredJwtException e) {
            throw new UserTokenException("User Token Expired!");
        }
    }

}
